package com.saleSystem.util;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.saleSystem.common.ServerResponse;

/**
 * 文件上传
 * @author guanwei
 *
 */
public class FileUpload {
	
	private static final Logger logger = LoggerFactory.getLogger(FileUpload.class);
	
	
    public static ServerResponse<String> uploadFile(MultipartFile file, HttpServletRequest request) {  
        
    	if(file.getSize()>1000000){
    		logger.debug("上传图片超过1MB！！");
    		return ServerResponse.createByError("上传失败！", null);  
    	}
    	
    	String fileName = file.getOriginalFilename();  
        String path=request.getSession().getServletContext().getRealPath("image/");  
        System.out.println(path);
        File tempFile = new File(path, new Date().getTime() + String.valueOf(fileName));  
        if (!tempFile.getParentFile().exists()) {  
            tempFile.getParentFile().mkdir();  
        }  
        if (!tempFile.exists()) {  
            try {
				tempFile.createNewFile();
			} catch (IOException e) {
				logger.debug("上传图片发生错误！",e);
				return ServerResponse.createByError("上传失败！", null);
			}  
        }  
        try {
			file.transferTo(tempFile);
		} catch (IllegalStateException e) {
			logger.debug("上传图片发生错误！",e);
			return ServerResponse.createByError("上传失败！", null); 
			
		} catch (IOException e) {
			logger.debug("上传图片发生错误！",e);
			return ServerResponse.createByError("上传失败！", null); 
		}  
        return ServerResponse.createBySuccess("上传成功！", "/image/" + tempFile.getName());  
    }  
    
}
